//
//  SHPE_CCViewController.m
//  SHPE CC
//
//  Created by Alex Muller on 3/16/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "SHPE_CCViewController.h"
#import "CustomCell.h"
#import "CustomCellWhatToDo.h"
#import <QuartzCore/QuartzCore.h>
#import "MoreInfo.h"
#import "Conference.h"
#import "Venue.h"
#import "Speaker.h"
#import "Location.h"

@implementation SHPE_CCViewController

@synthesize tableview;
@synthesize managedObjectContext;
@synthesize fetchController;
@synthesize confImage, confTitle, startDate, endDate;
@synthesize fetchedConf = _fetchedConf;

- (void)dealloc
{
    [super dealloc];
    self.fetchedConf = nil;
    [startDate release];
    [endDate release];
    [confImage release];
    [confTitle release];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSFetchRequest *confRequest = [[[NSFetchRequest alloc] init] autorelease];
    [confRequest setEntity:[NSEntityDescription entityForName:@"Conference" inManagedObjectContext:managedObjectContext]];
    
    NSError *error = nil;
    
    NSSortDescriptor *sortDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"id" ascending:YES] autorelease];
    NSArray *sortDescriptors = [[[NSArray alloc] initWithObjects:sortDescriptor, nil] autorelease];
    [confRequest setSortDescriptors:sortDescriptors];
    
    self.fetchedConf = [managedObjectContext executeFetchRequest:confRequest error:&error];
                        
    //if (_fetchedConf == nil) {
    //    NSLog(@"NO ITEMS WERE FETCHED");
    //}
    

}


- (id)initWithContext:(NSManagedObjectContext *)conf {
    [super init];
    [self setManagedObjectContext:conf];
    return self;
}
                            
                            
- (void)viewDidUnload
{
    [super viewDidUnload];
    
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_fetchedConf count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if((selectedCellIndexPath != nil) && ([selectedCellIndexPath isEqual:indexPath])) {
        return 226; 
    } else {
        return 100; 
    } 
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    tableview.layer.cornerRadius = 10;
    tableview.backgroundColor = [UIColor clearColor];
    Conference *conf = [_fetchedConf objectAtIndex:indexPath.row];
    confImage = [[UIImage alloc] init];
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
    startDate = [[formatter stringFromDate:conf.startDate] retain];
    endDate = [[formatter stringFromDate:conf.endDate] retain];
    confTitle = conf.name;
    if (conf.thumbnailData) {
        confImage = [UIImage imageWithData:conf.thumbnailData];
    } else {
        confImage = [UIImage imageNamed:@"noImage"];
    }
    
    if(selectedCellIndexPath != nil && [selectedCellIndexPath isEqual:indexPath]) {
        tableView.allowsSelection = NO;
        tableView.scrollEnabled = NO;
		static NSString *CustomCellIdentifier = @"CustomCellDetail";
		CustomCellWhatToDo *cell = (CustomCellWhatToDo *)[tableView dequeueReusableCellWithIdentifier: CustomCellIdentifier];
        
		if (cell == nil) {
            cell = [[[CustomCellWhatToDo alloc] initWithFrame:CGRectZero reuseIdentifier:CustomCellIdentifier] autorelease];
        }
        [cell.back addTarget:self action:@selector(backToList:) forControlEvents:UIControlEventTouchUpInside];
        [cell.moreInfo addTarget:self action:@selector(moreInfoButton:) forControlEvents:UIControlEventAllTouchEvents];
        /*if ([[_fetchedConf objectAtIndex:indexPath.row] twitter]) {
            cell.twitter.hidden = NO;            
        } else {
            cell.twitter.hidden = YES;
        }*/
        cell.imageView.image = confImage;
        cell.confName.text = confTitle;
        [tableView scrollToRowAtIndexPath:selectedCellIndexPath atScrollPosition:UITableViewScrollPositionMiddle animated:YES];
        //cell.selectionStyle = UITableViewCellSelectionStyleNone;        
        
        return cell;
    } else {
        
        tableView.allowsSelection = YES;
        tableView.scrollEnabled = YES;
        static NSString *CellIdentifier = @"CustomCell";
        
        CustomCell *customCell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (customCell == nil) {
            customCell = [[[CustomCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
        }
    
        customCell.selectionStyle = UITableViewCellSelectionStyleNone;
        customCell.primaryLabel.text = confTitle;
        customCell.secondaryLabel.text = startDate;
        customCell.backgroundColor = [UIColor blackColor];
        customCell.imageView.image = confImage;

        return customCell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    selectedCellIndexPath = indexPath; 
    
    //Use this to animate cell switching
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationMiddle];
    
    if(selectedCellIndexPath != nil && [selectedCellIndexPath isEqual:indexPath]) {
        [self.tableview reloadData];
	}
}

- (void)backToList:(id)selector{
    NSIndexPath *oldPath;
    oldPath = selectedCellIndexPath;
    selectedCellIndexPath = nil;
    
    [self.tableview reloadData];
    [self.tableview reloadRowsAtIndexPaths:[NSArray arrayWithObject:oldPath] withRowAnimation:UITableViewRowAnimationFade];
    
}

- (void)moreInfoButton:(id)selector{
    MoreInfo *mi= [[MoreInfo alloc] initWithNibName:@"MoreInfo" bundle:nil];
    [mi setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    [self presentModalViewController:mi animated:YES];
    //NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    //[formatter setDateFormat:@"MM/dd/yyyy HH:mm:ss"];
    //startDate = [formatter stringFromDate:[[_fetchedConf objectAtIndex:selectedCellIndexPath.row] startDate]];
    //endDate = [formatter stringFromDate:[[_fetchedConf objectAtIndex:selectedCellIndexPath.row] endDate]];
    mi.description.text = [[_fetchedConf objectAtIndex:selectedCellIndexPath.row] desc];
    mi.confTitle.text = confTitle;
    mi.begDate.text = startDate;
    mi.endingDate.text = endDate;
    mi.image.image = confImage;
    mi.confLoc = [[[_fetchedConf objectAtIndex:selectedCellIndexPath.row] location] retain];    
    mi.toRecipients = [NSArray arrayWithObject:[[_fetchedConf objectAtIndex:selectedCellIndexPath.row] email]];
    mi.speakerList = [[[_fetchedConf objectAtIndex:selectedCellIndexPath.row] speakers] allObjects];    
    mi.venueList = [[[_fetchedConf objectAtIndex:selectedCellIndexPath.row] venues] allObjects];
    mi.sessionList = [[[_fetchedConf objectAtIndex:selectedCellIndexPath.row] sessions] allObjects];
    [mi release];
    }

- (IBAction)aboutButton {
    NSString *aboutBody = [NSString stringWithFormat:@"Thank you for using the SHPE Conference Companion! This application was designed by Alex Muller and Richard Kirk, both undergraduates at The Florida State University. If you would like to send them an email, please feel free to use the link below to contact them."];
    UIAlertView *about = [[UIAlertView alloc] initWithTitle:@"About SHPE Conference Companion"
                                                    message:aboutBody
                                                   delegate:self
                                          cancelButtonTitle:@"OK"
                                          otherButtonTitles:@"Email Us", nil];
    [about show];
    [about release];
}

- (void)alertView:(UIAlertView *)alertView 
clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex == 0)
	{
		return;
	} else {
		if ([MFMailComposeViewController canSendMail]) {
            MFMailComposeViewController *picker = [[[MFMailComposeViewController alloc] init] autorelease]; 
            picker.mailComposeDelegate = self;
            
            NSArray *toRecipients = [NSArray arrayWithObjects:@"asm09@fsu.edu", @"rbk08@fsu.edu", nil]; 
            [picker setToRecipients:toRecipients];
            [self presentModalViewController:picker animated:YES];
        } else {
            NSString *body = @"Device is unable to send emails because there are no accounts set up. Please add an account using the Mail application.";
            UIAlertView *error = [[UIAlertView alloc] initWithTitle:@"Cannot Compose Email"
                                                            message:body 
                                                           delegate:self 
                                                  cancelButtonTitle:@"Ok" 
                                                  otherButtonTitles:nil];
            [error show];
            [error release];
        }
	}
}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error { 
        [controller dismissModalViewControllerAnimated:YES];
}


@end